package com.tedu.brand.controller;

import com.tedu.brand.pojo.Brand;
import com.tedu.brand.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
public class BrandController {
    @Autowired
    private BrandService brandService;

    /*
     * http://localhost:8080/brand/doFindBrands
     * http://localhost:8080/brand/doFindBrands/小米
     */
    @RequestMapping({"/brand/doFindBrands/{name}", "/brand/doFindBrands"})
    public String doFindBrands(@PathVariable(required = false) String name, Model model) {
        List<Brand> list = brandService.findBrands(name);
        model.addAttribute("list", list);
        return "brand/brand";
    }

    @RequestMapping("/brand/doAdd")
    public String doAdd() {
        return "brand/brand-add";
    }

    @RequestMapping("/brand/doFindById/{id}")
    public String doFindById(@PathVariable Long id, Model model) {
        Brand brand = brandService.findById(id);
        model.addAttribute("brand", brand);
        return "brand/brand-update";
    }

    @RequestMapping(value = "/brand/doSaveBrand", method = RequestMethod.POST)
    public String doSaveBrand(Brand brand, Model model) {
        brandService.insertBrand(brand);
        List<Brand> list = brandService.findBrands(null);
        model.addAttribute("list", list);
        return "brand/brand";
    }

    @RequestMapping(value = "/brand/doUpdateBrand", method = RequestMethod.POST)
    public String doUpdateBrand(Brand brand, Model model) {
        brandService.updateBrand(brand);
        List<Brand> list = brandService.findBrands(null);
        model.addAttribute("list", list);
        return "brand/brand";
    }

    @RequestMapping("/brand/doDeleteBrand/{id}")
    public String doDeleteBrand(@PathVariable Long id, Model model) {
        brandService.deleteBrand(id);
        List<Brand> list = brandService.findBrands(null);
        model.addAttribute("list", list);
        return "brand/brand";
    }
}
